<template>
    <div class="brs bg-fff pl-10 pr-10 pt-10 pb-5 bs">
        <!-- 头部部分 -->
        <div class="flex jc-sb">
            <div class="flex aic jc-sb">
                <span class="fwb">MA221245857Q</span>
                <span class="ml-20 fwb f14">Dec 12th 2022 PM 204</span>
            </div>
            <div>
                <el-button @click="add" plain>New</el-button>
                <el-button @click="save" type="success" plain>Save</el-button>
                <el-button @click="orderPopup" type="primary" plain>Add to Order</el-button>
                <el-button @click="rfqPopup" type="primary" plain>From RFQ</el-button>
                <el-button @click="del" type="primary">Delete</el-button>
            </div>
        </div>

        <div class="flex aic jc-sb ">
            <div class="flex w50p ">
                <div class="w50p">
                    <p>Supplier:</p>
                    <p class="f14">kemol Automotion</p>
                </div>
                <div>
                    <p>Client:</p>
                    <!-- <p>{{tableData.customer.company.CompanyName}}</p> -->
                    <p class="f14">哈哈哈哈哈哈哈哈哈哈哈</p>
                </div>
            </div>

            <div class="flex jc-sb w50p">
                <div>
                    <el-select v-model="profit" class="w25p" @change="unifiedProfit" placeholder="Profit">
                        <el-option v-for="item in profitArr" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-select v-model="leading" class="w25p ml-10" @change="unifiedLeading" placeholder="LEADING">
                        <el-option v-for="item in newLeading" :key="item.case" :label="item.label" :value="item.case" />
                    </el-select>
                </div>
                <div>
                    <el-button @click="exportButton" type="primary">Excel</el-button> <!--导出按钮 -->
                    <el-dialog v-model="excelDialog" title="Select the required header" width="30%" align-center>
                        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                            @change="handleCheckAllChange">Check all</el-checkbox>
                        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                            <el-checkbox v-for="city in cities" :key="city" :label="city">{{
                                city
                            }}</el-checkbox>
                        </el-checkbox-group>
                        <template #footer>
                            <span class="dialog-footer">
                                <el-button @click="excelDialog = false">Cancel</el-button>
                                <el-button type="primary" @click="excel">
                                    Confirm
                                </el-button>
                            </span>
                        </template>
                    </el-dialog>
                </div>
            </div>
        </div>

        <p class="fa5 mt-10 mb-10"><span>QUOTATION DETAIL</span> <span>MA2212171285Q</span> - <span>RFQ
                JA221214545R</span></p>

        <!-- 添加到订单弹窗 -->
        <AddOrder ref="order" :newLeading="newLeading" :newCondition="newCondition"></AddOrder>
        <!-- 从询盘而来弹窗 -->
        <fromRfq ref="rfq" :newLeading="newLeading" :newCondition="newCondition" @update="update"></fromRfq>

        <!-- 中间部分 -->
        <div class="mt-5">
            <el-table :data="tableData.item" @selection-change="row" @cell-click="table" :row-class-name="rfqList"
                height="40.5vh" style="width: 100%">
                <el-table-column type="selection" width="30" />
                <el-table-column label="MODEL" min-width="200">
                    <template v-slot="model">
                        <el-select v-model="model.row.product.model" @change="chModel" @input="getModel"
                            @visible-change="visible" filterable placeholder="MODEL">
                            <el-option v-for="item in newModel" :key="item.id" :label="item.label" :value="item.id" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="BRAND" min-width="130">
                    <template v-slot="brand">
                        <el-select v-model="brand.row.brand.brand_name" @input="getBrand" @visible-change="visible"
                            filterable placeholder="BRAND">
                            <el-option v-for="item in newBrand" :key="item.id" :label="item.label" :value="item.id" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="QTY" width="80">
                    <template v-slot="qty">
                        <el-input v-model="qty.row.Qty" />
                    </template>
                </el-table-column>
                <!-- 售出价 -->
                <el-table-column align="center" label="PRICE" min-width="100">
                    <template v-slot="price">
                        <el-input v-model="price.row.purchase.quotation_price"
                            @input="inpPrice($event, price.row.purchase.purchase_price, price.row.purchase)" />
                    </template>
                </el-table-column>

                <!-- 利润 -->
                <el-table-column align="center" label="Profit" min-width="95">
                    <template v-slot="profit">
                        <div class="flex aic">
                            <el-input v-model="profit.row.purchase.profit_rate"
                                @input="newSale($event, profit.row.purchase.purchase_price, profit.row.purchase)" />
                            <p class="f18">%</p>
                        </div>
                    </template>
                </el-table-column>
                <!-- 成本价 -->
                <el-table-column align="center" label="COST" min-width="80">
                    <template v-slot="cost">
                        <el-input v-model="cost.row.purchase.purchase_price"
                            @input="inpCost($event, cost.row.purchase.profit_rate, cost.row.purchase)" />
                    </template>
                </el-table-column>
                <el-table-column align="center" label="LEADING" width="120">
                    <template v-slot="leading">
                        <el-select v-model="leading.row.purchase.leadingtime" filterable placeholder="Select">
                            <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                :value="item.case" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="CONDITION" width="150">
                    <template v-slot="condition">
                        <el-select v-model="condition.row.purchase.product_condition" filterable placeholder="Select">
                            <el-option v-for="item in newCondition" :key="item.label" :label="item.label"
                                :value="item.case" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="RFQ FROM" width="100">
                    <template v-slot="rfq">
                        <el-input :value="rfq.row.product.model ? rfqId : ''" disabled />
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import * as $axios from '../../../api/index'
import { ElMessage } from 'element-plus'
import AddOrder from './components/AddOrder.vue';
import fromRfq from './components/FromRfq.vue';
import { useDemoStore } from '../../../pinia/index'
const store = useDemoStore()

const props = defineProps({
    rfqId: String,
    newLeading: Array,
    newCondition: Array
})

// 表格列表
const tableData = ref([])
const getTable = () => {
    const data = {
        token: store.token,
        inquiry_id: props.rfqId
    }
    $axios.$orderget_order_purchase(data).then(res => {
        tableData.value = res.data
        tableData.value.item.push({  //增加一条空白列
            "Qty": '',
            "product": {

            },
            "purchase": {

            },
            "brand": {
                "brand_name": ""
            },
        })
        product_id.value = tableData.value.item[0].product_id
        model.value = tableData.value.item[0].product.model
        emits('product')
        // console.log(res.data.item[0].product_id)
    })
}

watch(props, () => {
    getTable()
})


// 获取利润，计算售出价
const getprofit = ref(0)
const newSale = (e, value, data) => {  //获取利润
    getprofit.value = ((e / 100) * (value || 0 * 1) + (value || 0) * 1).toFixed(2)   //计算售出价
    data.quotation_price = getprofit.value
    console.log(e, value)
}


// 获取售出价,计算利润
const newProfit = ref()  //利润
const inpPrice = (e, value, data) => {
    newProfit.value = ((e - value * 1) / value * 1 * 100).toFixed(2)  //计算利润比
    data.profit_rate = newProfit.value != 'NaN' ? newProfit.value : 0
}

// 获取成本价,计算售出价
const tmoney = ref(0)  //售出价
const inpCost = (e, value, data) => {
    tmoney.value = (e * ((value || 0) / 100) + e * 1).toFixed(2)  //计算售出价
    data.quotation_price = tmoney.value
    // console.log(e, (value||0 )/ 100)
}

// 多选框
const id = ref([])
const row = (value) => {
    id.value = value.map(item => {
        return item.purchase.inquiry_item_info_id
    })
    console.log(id.value)
}

// 点击表格触发事件
const product_id = ref('')
const model = ref('')
const table = (row) => {
    product_id.value = row.product_id
    model.value = row.product.model
    emits('product')
    // console.log(row)
}
// 表格高亮
const rfqList = ({
    row,
    rowIndex,
}) => {
    if (row.product_id === product_id.value) {
        return 'success-row'
    }
    return ''
}

// 新增
const add = () => {
    save()
    tableData.value.item = []
    for (let i = 0; i < 5; i++) {
        tableData.value.item.push({  //增加空白列
            "Qty": '',
            "msg": 1,
            "product": {

            },
            "purchase": {

            },
            "brand": {
                "brand_name": ""
            },
        })
    }
}

// 保存
const save = () => {
    const quotation = ref([])
    const saveData = ref([])
    tableData.value.item.forEach(item => {
        if (item.product.model) {
            saveData.value.push(item)
        }
    });
    quotation.value = saveData.value.map(item => {
        return {
            "inquiry_item_info_id": item.purchase.inquiry_item_info_id || '',
            "quotation_price": item.purchase.quotation_price,
            "purchase_price": item.purchase.purchase_price,
            "profit_rate": item.purchase.profit_rate,
            "product_id": typeof item.product.model === 'string' ? item.product.product_id : item.product.model,
            "leadingtime": item.purchase.leadingtime,
            "product_condition": item.purchase.product_condition,
            "brand_id": typeof item.brand.brand_name == 'string' ? item.brand.brand_id : item.brand.brand_name,
            "purchaser_id": item.purchaser_id || '',
            "qty": item.Qty,
        }
    })
    console.log(quotation.value)


    const data = {
        token: store.token,
        inquiry_id: props.rfqId,
        quotation: quotation.value
    }
    if (tableData.value.item[0].msg == 1) { //新建
        $axios.$orderNew_quotation_fun(data).then(res => {
            if (res.Status === 0) {
                emits('save')
                ElMessage({
                    message: 'Successful preservation',
                    type: 'success',
                })
            }
            console.log(res)
        })
    } else {
        $axios.$orderSet_quotation(data).then(res => {
            if (res.Status === 0) {
                tableData.value.item[0].msg == 1 || getTable()
                ElMessage({
                    message: 'Successful preservation',
                    type: 'success',
                })
            }
            console.log(res)
        })
    }
}
// 删除
const del = () => {
    const data = {
        token: store.token,
        inquiry_item_info_id: id.value
    }
    $axios.$orderDel_quotation(data).then(res => {
        if (res.Status === 0) {
            getTable()
            ElMessage({
                message: 'Successful preservation',
                type: 'success',
            })
        }
        console.log(res)
    })
}

// 判断有没有选择列，没有选择就提示选择
const excelDialog = ref(false)
const exportButton = () => {
    if (id.value[0]) {
        excelDialog.value = true
    } else {
        ElMessage({
            message: 'Please select a quotation first',
            type: 'warning',
        })
    }
}

// 选择报价表头导出
const checkAll = ref(false)
const isIndeterminate = ref(true)
const checkedCities = ref([])
const cities = ["model", "brand_name", "purchase_price", "leadingtime", "product_condition", "quotation_price", "Effective", "Reliability"]

const handleCheckAllChange = (val) => {
    checkedCities.value = val ? cities : []
    isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === cities.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < cities.length
}

// 下载报价
const excel = () => {
    const data = {
        token: store.token,
        inquiry_item_info_id: id.value,
        header: checkedCities.value
    }
    $axios.$orderPull_excel(data).then(res => {
        excelDialog.value = false
        window.open(res.data)
        // console.log(checkedCities.value)
    })
}


// 利润数据
const profit = ref('')
const profitArr = ref([
    {
        label: '10%',
        value: 10
    },
    {
        label: '15%',
        value: 15
    },
    {
        label: '20%',
        value: 20
    },
    {
        label: '25%',
        value: 25
    },
    {
        label: '30%',
        value: 30
    },
    {
        label: '35%',
        value: 35
    },
    {
        label: '40%',
        value: 40
    },
    {
        label: '45%',
        value: 45
    },
    {
        label: '50%',
        value: 50
    },
])

// 批量更改利润
const unifiedProfit = (data) => {
    tableData.value.item.forEach(item => {
        if (item.product.model) {
            item.purchase.profit_rate = data
            item.purchase.quotation_price = ((data / 100) * (item.purchase.purchase_price || 0 * 1) + (item.purchase.purchase_price || 0) * 1).toFixed(2)
        }
        // console.log(item)
    })
}

// 批量更改指标
const leading = ref('')
const unifiedLeading = (data) => {
    tableData.value.item.forEach(item => {
        if (item.product.model) {
            item.purchase.leadingtime = data
        }
        // console.log(item)
    })
}

//model选择框，判断最后一个model有没有值，有就新增一条空白项
const chModel = () => {
    const model = ref('')
    model.value = tableData.value.item[tableData.value.item.length - 1].product.model
    if (model.value) {
        tableData.value.item.push({  //增加空白列
            "Qty": '',
            "product": {

            },
            "purchase": {

            },
            "brand": {
                "brand_name": ""
            },
        })
    }
}

// 选择框打开关闭触发
const visible = () => {
    inpModel.value = '' //清空数组
    inpBrand.value = ''
}

// model
const newModel = ref([])
const inpModel = ref('')
var timer
const getModel = (text) => {
    if (text.data != null) {
        inpModel.value += text.data
    } else if (text.data == null) {
        inpModel.value = inpModel.value.slice(0, -1)
    }
    const data = {
        token: store.token,
        keywords: inpModel.value
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
        $axios.$product_find(data).then(res => {
            console.log(res.data)
            newModel.value = res.data.map(item => {
                return {
                    'label': item.model,
                    'id': item.product_id
                }
            })
        })
    }, 300)
}

// brand
const newBrand = ref([])
const inpBrand = ref('')
var timer
const getBrand = (text) => {
    if (text.data != null) {
        inpBrand.value += text.data
    } else if (text.data == null) {
        inpBrand.value = inpBrand.value.slice(0, -1)
    }
    const data = {
        token: store.token,
        keywords: inpBrand.value
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
        $axios.$product_brand(data).then(res => {
            console.log(res.data)
            newBrand.value = res.data.map(item => {
                return {
                    'label': item.brand_name,
                    'id': item.brand_id
                }
            })
        })
    }, 300)
    console.log(inpBrand.value)
}

// 添加到订单弹窗
const order = ref()
const orderPopup = () => {
    order.value.open()
}

// 从询盘而来弹窗
const rfq = ref()
const rfqPopup = () => {
    rfq.value.rfq()
}



//暴露给父组件
defineExpose({
    product_id,
    model
})

const update = ()=>{
    emits('save')
}

// 暴露product事件
const emits = defineEmits(['product', 'save'])

</script>

<style lang="less" scoped>
.el-button.is-plain {
    border: 1px solid #7da3f3;
    color: #7da3f3;
    background-color: #fff;
}
</style>